<?php 
namespace App\Http\Components;

use App\Http\Components\AppComponent;

use DB;
use App\library\RongCloudServer;
use App\Models\MessageGroupModel;
use App\Models\OrderModel;
/**
* 
*/
class RongCloudComponent extends AppComponent{
	
	public function __construct(){
        parent::__construct();
	}

    /*向融云注册用户*/
    public static function register($user_id, $nick_name, $avatar){
        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        app()->configure('ppurl');
        $ppurl = config('ppurl');
        $def_avatar = $ppurl['img_url'].$ppurl['def_avatar'];
        $avatar = ($avatar)?$avatar:$def_avatar;

        $result = $server->getToken($user_id, $nick_name, $avatar);
        $outer_response = json_decode($result,true);
        if ($result && $outer_response && isset($outer_response['token'])) {
            // $other['user_base_info'] = $userProfile->toArray();
            // $other['outer_response'] = $outer_response;
            // $other['message_token'] = $outer_response['token'];
            return $outer_response['token'];
        }else{
            $other['outer_response'] = $outer_response;
            return SELF::_json('0','聊天系统注册失败:'.$server->errmsg,'',$other);
        }
    }
    //更新融云用户信息
    public static  function update($user_id, $nick_name, $avatar){
        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        app()->configure('ppurl');
        $ppurl = config('ppurl');
        $def_avatar = $ppurl['img_url'].$ppurl['def_avatar'];
        $avatar = ($avatar)?$avatar:$def_avatar;

        $result = $server->userRefresh($user_id, $nick_name, $avatar);
        $outer_response = json_decode($result,true);
        if ($result && $outer_response && $outer_response['code'] == 200) {
            return true;
        }else{
            return SELF::_json('0','用户信息更新失败:'.$server->errmsg);
        }
    }


    public static function system_register($user_id,$nick_name,$avatar){
        return SELF::register($user_id, $nick_name, $avatar);
    }

    /**
     * 获取容云api接口
     */
    public static function server(){
        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        return new RongCloudServer($app_key,$app_secret);
    }

    /**
     *  给一个或多个用户发送系统消息，系统消息通知者为10000号
     * @param to_user 接收者id 
     * @param message app接收并显示的信息 
     * @param link  保存到数据库给系统消息点击用的外链 
     * @param   发送到app进行解析的 
     */
    public static function system_publish($to_user,$message,$desc = '',$link = '',$link_type = ''){
        app()->configure('ppurl');
        $h5_url = config('ppurl.h5_url');
        $system_id = '1111';

//        $type_ids = array(
//            'me'=>'1111', // 与我相关
//            'friend'=>'2222', // 好友关系
//            'team'=>'3333', // 入队申请
//            'corps'=>'4444', // 战队操作
//            'match'=>'5555', // 约战相关
//        );
//
//        $h5_link_type_arr = array(
//            'request_enroll_detail' => array(
//                'url' => $h5_url.'/statics/fromCre/convene_details.html?enroll_id=',
//                'type' => 'match',
//            ),
//            'response_enroll_detail' =>  array(
//                'url' => $h5_url.'/statics/fromCre/conveneDetailsRes.html?enroll_id=',
//                'type' => 'match',
//            ),
//            'request_detail' =>  array(
//                'url' => $h5_url.'/statics/fromCre/initiate-match.html?request_id=',
//                'type' => 'match',
//            ),
//            'challenge_detail' =>  array(
//                'url' => $h5_url.'/statics/fromCre/Challenge-fightU.html',
//                'type' => 'match',
//            ),
//            'team_request' =>  array(
//                'url' => $h5_url.'/statics/fromCre/new-apply.html?corps_id=',
//                'type' => 'team',
//            ),
//            'corps_detail' =>  array(
//                'url' => $h5_url.'/statics/matchingRace/corpsDetail.html?corps_id=',
//                'type' => 'team',
//            ),
//        );
//
//        $native_link_type_arr = array(
//            'friend_request'=>array(
//                'url' => '',
//                'type' => 'friend',
//            ),
//            'moments_comment'=>array(
//                'url' => '',
//                'type' => 'me',
//            ),
//        );

        // app()->configure('account');
        // $app_key = config('account.rong_cloud_app_key');
        // $app_secret = config('account.rong_cloud_app_secret');
        $server = SELF::server();

        /*发送到用户id*/
        if (!is_array($to_user)) {
            $to_user = array($to_user);
        }
        $desc = $desc?$desc:$message;

        $content = json_encode(array('content'=>$message));
        // $pushContent = $message;
        // $pushData = json_encode(array('content'=>$message));

        $save_data = array();
//        if (isset($h5_link_type_arr[$link_type])) {
//            if(is_array($link)){
//                $query = http_build_query($link);
//                $link = $h5_link_type_arr[$link_type]['url'].$query;
//            }else{
//                $link = $h5_link_type_arr[$link_type]['url'].$link;
//            }
//            $type = $h5_link_type_arr[$link_type]['type'];
//        }
//        elseif (isset($native_link_type_arr[$link_type])) {
//            $link = $native_link_type_arr[$link_type]['url'];
//            $type = $native_link_type_arr[$link_type]['type'];
//        }elseif (isset($type_ids[$link_type])) {
//            $link = '';
//            $type = $link_type;
//            $link_type = 'look';
//        }else{
//            return false;
//        }

//        $system_id = $type_ids[$type];

        $new_data = array('message'=>$message,'desc'=>$desc,'link'=>$link,'link_type'=>$link_type);
        foreach ($to_user as $user_id) {
            $new_data['user_id'] = $user_id;
            $save_data[] = $new_data;
        }
        DB::table('message_system_publish')->insert($save_data);

        $return = $server->messageSystemPublish($system_id,$to_user,'RC:TxtMsg',$content);
        if (!$return) {
            SELF::_json('0',$server->errmsg);
        }
        return $return;
    }

    /**
     * 推送
     */
    public static function push($is_to_all = false,$user_list,$message,$desc,$link,$link_type = 'none',$order_id=''){
        $save_data = array();
        $platform = array('ios','android');
        $server = SELF::server();
        //推送信息基础数据
        $new_data = array('message'=>$message,'desc'=>$desc,'link'=>$link,'link_type'=>$link_type,'order_id'=>$order_id);
        if($link_type == 'order'){
            $new_data['message_type'] = 2;
        }else{
            $new_data['message_type'] = 1;
        }

        if(!$is_to_all){    //指定推送用户
            foreach($user_list AS $uitem){
                $new_data['user_id'] = $uitem;
                $save_data[] = $new_data;
            }
            DB::table('message_system_publish')->insert($save_data);
            $audience['userid'] = $user_list;
        }else{  //全部推送
            $user_list =  DB::table('user')->lists('user_id');

            foreach($user_list AS $uitem){
                $new_data['user_id'] = $uitem;
                $save_data[] = $new_data;
            }
            DB::table('message_system_publish')->insert($save_data);
        }

        $audience['is_to_all'] = $is_to_all;
        $notification['alert'] = empty($message)?$desc:$message;

        if($link_type == 'href'){
            $extras = array('link'=>$link,'link_type'=>$link_type);
        }elseif($link_type == 'order'){
            $order = OrderModel::where("order_id",$order_id)->first();
            if($order){
                $order = $order->toArray();
                if($order['user_id'] == $user_list[0]){  //我的订单
                    $order_type = 1;
                }else{  //我的约单
                    $order_type = 2;
                }
                $order_status = $order['status'];
                if($order['status'] == 4 || $order['status'] == 5){
                    $order_status = 4;
                }elseif($order['status'] == 6 || $order['status'] == 7){
                    $order_status = 5;
                }
                $extras = array('link_type'=>$link_type,'order_id'=>$order_id,'order_type'=>$order_type,'order_status'=>$order_status);
            }
        }else{
            $extras = array('link_type'=>$link_type);
        }

        $notification['ios']['extras'] = $extras;
        $notification['android']['extras'] = $extras;
        $result = $server->push($platform,$audience,$notification);

        return $result;
    }

    public static function groupCreate($user_id,$group_id,$gruop_name,$group_avatar = ''){
        $group_data = array(
            'group_id'=>$group_id,
            'nick_name'=>$gruop_name,
            'avatar'=>$group_avatar,
        );

        $message_group = MessageGroupModel::firstOrNew(['group_id'=>$group_id]);
        $message_group->user_id = $user_id;
        $message_group->nick_name = $gruop_name;
        $message_group->avatar = $group_avatar;
        $message_group->save();

        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        // $server->groupJoin('10000',$group_id,$gruop_name);
        return $server->groupJoin($user_id,$group_id,$gruop_name);
    }
    
    public static function groupJoin($user_id,$group_id,$gruop_name,$group_avatar = ''){
        $group_data = array(
            'group_id'=>$group_id,
            'nick_name'=>$gruop_name,
            'avatar'=>$group_avatar,
        );

        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        return $server->groupJoin($user_id,$group_id,$gruop_name);
    }

    /*单聊小灰条*/
    public static function notify($fromUserId, $toUserId , $message){

        $toUserId = is_array($toUserId)?$toUserId:array($toUserId);
        $objectName = "RC:InfoNtf";
        $content = json_encode( array("message"=>$message,"extra"=>""));

        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        return $server->messagePublish($fromUserId, $toUserId = array(), $objectName, $content);
    }

    /*群聊小灰条*/
    public static function groupNotify( $toGroupId , $message,$extra=""){

        $toGroupId = is_array($toGroupId)?$toGroupId:array($toGroupId);
        $objectName = "RC:InfoNtf";
        $content = json_encode( array("message"=>$message,"extra"=>$extra));

        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        return $server->messageGroupPublish('10000' , $toGroupId, $objectName, $content);
    }

    /*群聊成员*/
    public static function group_members($groupId){
        app()->configure('account');
        $app_key = config('account.rong_cloud_app_key');
        $app_secret = config('account.rong_cloud_app_secret');
        $server = new RongCloudServer($app_key,$app_secret);
        $result = $server->groupUserQuery($groupId);
        $members = json_decode($result,true);
        $member_ids = array();
        foreach($members['users'] as $member){
            $member_ids[] = $member['id'];
        }
        return $member_ids;
    }
}
